import instance from "./axiosInstance";

// 获取当前登录用户信息
export const getCurrentUser = async () => {
  try {
    const response = await instance({
      method: "GET",
      url: "/user/get",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });
    return response.data;
  } catch (error) {
    console.error("获取当前登录用户信息异常:", error);
    throw error;
  }
};

// 根据id获取用户
export const getUserById = async (id) => {
  try {
    const response = await instance({
      method: "GET",
      url: `/user/${id}`,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
    });
    return response.data;
  } catch (error) {
    console.error("根据id获取用户异常:", error);
    throw error;
  }
};

// 添加用户和地址
export const addUser = async (data) => {
  try {
    console.log("[API] 原始角色值:", data.userRole);

    const requestData = {
      id: data.id || 0,
      phone: data.phone || "",
      realName: data.realName || "",
      userName: data.userName || "",
      userRole: data.userRole || "",
      userProfile: data.userProfile || "",
      provinceCode: data.provinceCode || "",
      provinceName: data.provinceName || "",
      cityCode: data.cityCode || "",
      cityName: data.cityName || "",
      districtCode: data.districtCode || "",
      districtName: data.districtName || "",
      detailAddress: data.detailAddress || "",
    };

    console.log(
      "[API] 添加用户请求数据:",
      JSON.stringify(requestData, null, 2)
    );

    const response = await instance({
      method: "POST",
      url: "/user",
      headers: {
        "Content-Type": "application/json",
      },
      data: requestData,
    });

    console.log("[API] 添加用户响应:", JSON.stringify(response.data, null, 2));
    return response.data;
  } catch (error) {
    console.error("添加用户和地址异常:", error);
    throw error;
  }
};

// 管理员更新用户信息
export const updateUser = async (data) => {
  try {
    console.log("[API] 更新原始角色值:", data.userRole);

    const requestData = {
      id: data.id || 0,
      userName: data.userName || "",
      realName: data.realName || "", // 添加真实姓名字段
      phone: data.phone || "",
      userAvatar: data.userAvatar || "",
      userProfile: data.userProfile || "",
      userRole: data.userRole || "",
      updateTime: data.updateTime || "",
    };

    console.log(
      "[API] 更新用户请求数据:",
      JSON.stringify(requestData, null, 2)
    );

    const response = await instance({
      method: "POST",
      url: "/user/update",
      headers: {
        "Content-Type": "application/json",
      },
      data: requestData,
    });

    console.log("[API] 更新用户响应:", JSON.stringify(response.data, null, 2));
    return response.data;
  } catch (error) {
    console.error("管理员更新用户信息异常:", error);
    throw error;
  }
};

// 更新个人资料（不包含手机号）
export const updateSelfProfile = async (data) => {
  try {
    const response = await instance({
      method: "POST",
      url: "/user/me/update",
      headers: {
        "Content-Type": "application/json",
      },
      data: {
        id: data.id || 0,
        userName: data.userName || "",
        userAvatar: data.userAvatar || "",
        userProfile: data.userProfile || "",
        updateTime: data.updateTime || new Date().toISOString(),
      },
    });
    return response.data;
  } catch (error) {
    console.error("更新个人资料异常:", error);
    throw error;
  }
};

// 管理员删除用户
export const deleteUser = async (id) => {
  try {
    console.log("[API] 删除用户ID:", id);

    const response = await instance({
      method: "DELETE",
      url: "/user",
      headers: {
        "Content-Type": "application/json",
      },
      data: {
        id: id,
      },
    });

    console.log("[API] 删除用户响应:", JSON.stringify(response.data, null, 2));
    return response.data;
  } catch (error) {
    console.error("管理员删除用户异常:", error);
    throw error;
  }
};

// 根据创建者id分页获取用户封装列表
export const getUserListByCreator = async (params = {}) => {
  try {
    const requestData = {
      pageNum: params.pageNum || 1,
      pageSize: params.pageSize || 10,
      sortField: params.sortField || "",
      sortOrder: params.sortOrder || "",
      id: params.id || 0,
      createUserId: params.createUserId || 0,
      phone: params.phone || "",
      realName: params.realName || "",
      userName: params.userName || "",
      userProfile: params.userProfile || "",
      userRole: params.userRole || "",
    };

    console.log(
      "[API] 查询用户列表请求:",
      JSON.stringify(requestData, null, 2)
    );

    const response = await instance({
      method: "POST",
      url: "/user/list/page/vo",
      headers: {
        "Content-Type": "application/json",
      },
      data: requestData,
    });

    console.log(
      "[API] 查询用户列表响应:",
      JSON.stringify(response.data, null, 2)
    );
    return response.data;
  } catch (error) {
    console.error("根据创建者id分页获取用户封装列表异常:", error);
    throw error;
  }
};

// 超级管理员分页查询全部用户(多维度条件)
export const getSuperAdminUserList = async (params = {}) => {
  try {
    const requestData = {
      pageNum: params.pageNum || 1,
      pageSize: params.pageSize || 10,
      sortField: params.sortField || "",
      sortOrder: params.sortOrder || "",
      id: params.id || 0,
      createUserId: params.createUserId || 0,
      phone: params.phone || "",
      realName: params.realName || "",
      userName: params.userName || "",
      userProfile: params.userProfile || "",
      userRole: params.userRole || "",
    };

    console.log(
      "[API] 超级管理员查询用户请求:",
      JSON.stringify(requestData, null, 2)
    );

    const response = await instance({
      method: "POST",
      url: "/user/list/page/super",
      headers: {
        "Content-Type": "application/json",
      },
      data: requestData,
    });

    console.log(
      "[API] 超级管理员查询用户响应:",
      JSON.stringify(response.data, null, 2)
    );
    return response.data;
  } catch (error) {
    console.error("超级管理员分页查询全部用户异常:", error);
    throw error;
  }
};

// 统一的API对象
export const userApi = {
  getCurrentUser,
  getUserById,
  addUser,
  updateUser,
  updateSelfProfile,
  deleteUser,
  getUserListByCreator,
  getSuperAdminUserList,
};
